package com.atguigu.gmall.product.controller;

import com.atguigu.gmall.common.result.Result;
import org.apache.commons.io.FilenameUtils;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.csource.common.MyException;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author ：MJS
 * @date ：Created in 2021/5/10  15:05
 * @description：TODO
 */
@RestController
@RequestMapping("/admin/product")
public class FileUploadController {
    @Value("${image.url}")
    private String url;
    //上传图片
    @PostMapping("/fileUpload")
    public Result fileupload(MultipartFile file){
        try {
            String path = ClassUtils.getDefaultClassLoader().getResource("fds_client.conf").getPath();
            //0.配置跟踪器的ip：port
            ClientGlobal.init(path);
            //1.创建TrackerClient客户端   192.168.6.105
            TrackerClient trackerClient =new TrackerClient();
            //2.连接TrackerServer端
            TrackerServer trackerServer = trackerClient.getConnection();
            //3.创建存储节点和客户端
            StorageServer storageServer=null;
            StorageClient1 storageClient1=new StorageClient1(trackerServer,storageServer);
            //4.上传文件
            String extension = FilenameUtils.getExtension(file.getOriginalFilename());
            String fileId = storageClient1.upload_file1(file.getBytes(),
                    extension, null);
            System.out.println(url+fileId);
            return Result.ok(url+fileId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
